package cn.edu.xmist.supermarketsys.controller;

import cn.edu.xmist.supermarketsys.Util.ObjtoLayJson;
import cn.edu.xmist.supermarketsys.Util.Strs;
import cn.edu.xmist.supermarketsys.entity.House;
import cn.edu.xmist.supermarketsys.entity.Product;
import cn.edu.xmist.supermarketsys.service.HouseService;
import cn.edu.xmist.supermarketsys.service.ProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/house")
public class HouseController {
    @Autowired
    private HouseService houseService;
    @Autowired
    private ProductService wareService;

    public static String[] columns = {"id", "houseCode", "houseName"};

    @RequestMapping("/list")
    public String list(Integer page, Integer limit) throws Exception {
        List<House> list = houseService.list();

        return ObjtoLayJson.ListtoJson(list, columns);
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(House house) {
        if (house.getId() == null) {
            QueryWrapper<House> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("house_code", house.getHouseCode());
            List<House> list = houseService.list(queryWrapper);
            if (list.size() > 0) {
                return Strs.FAIL_RETURN_JSON;
            }
        }
        Boolean flag = houseService.saveOrUpdate(house);
        return Strs.SUCCESS_RETURN_JSON;
    }

    @RequestMapping("/deleteById")
    public String deleteById(Long id) {
        House house = houseService.getById(id);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("house_code", house.getHouseCode());
        List<Product> list = wareService.list(queryWrapper);
        if (list.size() > 0) {
            return Strs.FAIL_RETURN_JSON;
        }
        Boolean flag = houseService.removeById(id);
        return Strs.SUCCESS_RETURN_JSON;
    }

}
